#!/usr/bin/env bash

set -e

source $SNAP/actions/common/utils.sh

use_snap_env

function help() {
    echo "Available subcommands are:"
    for i in ${SNAP}/microk8s-*.wrapper; do
        echo -e "\t$(basename ${i} | sed 's/microk8s-//g' | sed 's/.wrapper//g')"
    done
    echo -e "\tinspect"
    plugins="$(find ${SNAP_COMMON}/plugins/* 2> /dev/null)"
    if [ ! -z "$plugins" ]; then
            echo "Available subcommands from addons are:"
            for i in "${SNAP_COMMON}/plugins/"*; do
                echo -e "\t$(basename "${i}")"
            done
    fi
}

if [ -z "$1" ]; then
    help
    exit 1
fi

readonly APP="$1"
shift

if [ -f "${SNAP}/microk8s-${APP}.wrapper" ]; then
    "${SNAP}/microk8s-${APP}.wrapper" "$@"
    readonly EXIT="$?"
elif [ "${APP}" == "inspect" ]; then
    run_with_sudo preserve_env ${SNAP}/inspect.sh "$@"
    readonly EXIT="$?"
elif [ "${APP}" == "help" ] || [ "${APP}" == "--help" ] || [ "$APP" == "-h" ]; then
    help
    readonly EXIT="0"
elif [ -f "${SNAP_COMMON}/plugins/${APP}" ]; then
    "${SNAP_COMMON}/plugins/${APP}" "$@"

    readonly EXIT="$?"
else
    echo "'${APP}' is not a valid MicroK8s subcommand."
    help
    readonly EXIT="1"
fi

exit ${EXIT}
